<template>
	<view class="pBox" v-show="showStatus" :style="{'overflow-y':showTask==true?'none':'auto'}">
		<view class="header_box"  >
			<image :src="setData.banner" mode="widthFix"></image>
			<span class="share" type="default" @click="nextPage(0)">分享活动</span>
			<span class="prize" type="default" @click="nextPage(1)">我的奖品</span>
		</view>
		<view class="container" :style="{'background': setData.bgcolor || '#FFBE9E'  }">
			<view class="banner_bg" v-if="setData.show_winner && activityText.winners.length>0">
				<view class="name_banner" id="banner" :style="[{'animation-duration':bannerDelay,'width':bannerWidth+'px'}]">
					<view class="item" :class="{'banner_item':true}" v-for="(item,index) in activityText.winners" :key="index">
						<view class="avatr" >
							<image :src="item.avatar"   @error="imageError($event, index)"/>
						</view>
						<span>{{item.message}}</span>
					</view>
				</view>
			</view>
			<view class="content_box">
				<!--  -->
				<view class="nums" v-if="setData.show_data">
					<view class="num">
						<span>{{activityText.view_num || 0}}</span>
						<span>浏览量</span>
					</view>
					<view class="divider"></view>
					<view class="num">
						<span>{{activityText.play_num || 0}}</span>
						<span>参与量</span>
					</view>
					<view class="divider"></view>
					<view class="num">
						<span>{{activityText.win_num || 0}}</span>
						<span>中奖数</span>
					</view>
				</view>
				<view class="g_model">
					<span class="title" v-if="setData.show_title">{{data.title}}</span>
					<span class="time">活动时间：{{settime(data.start_time)}}-{{settime(data.expire_time)}}</span>
					<view class="d_content" :style="[{'background':'url('+gBackground+') no-repeat center center','boxShadow':'0rpx 6rpx 20rpx 1rpx '+gShadow}]">
						<view class="do">
							<view class="gua_img_box" v-if="pageStatus == 3 && checkHost(setData.layer_banner) " @click="handlerGua">
								<img :src="setData.layer_banner"></img>
							</view>
							<view  class="show_time" v-if="pageStatus >= 0 & pageStatus<3" @click="handlerGua">
								<span  v-if="pageStatus == 0">活动即将开始</span>
								<span  v-if="pageStatus == 0">{{showDate.day}}天{{showDate.hours}}小时{{showDate.minues}}分{{showDate.ms}}秒</span>
								<span v-if="pageStatus == 1">活动已结束</span>
								<span  v-if="pageStatus == 2">您还未登录</span>
								<span  v-if="pageStatus == 2">请先<span style="color: #4379A8;" @click="login">登录</span></span>
							</view>
							<view v-if="showStatus" class="gua"  @touchmove.stop.prevent="moveHandle">
								<guaCanvas :isInit="guaData.resetGua" :gdata="guaData" :isAllow="guaData.isAllow" @startTouch="getPrize" @finish="handlerGuafinish"></guaCanvas>
							</view>

						</view>
					</view>
					<view class="chance_msg" v-if="chance!=-1">您还剩余<span>{{chance}}</span>次刮奖机会<view v-if="activityText.has_task&&taskMenuData.length>0" class="get_more_times">，去<span @click="openTaskCenter">领次数</span></view></view>
					<view class="nochance"></view>
				</view>
				<view style="box-shadow: 0px 0px 20rpx 1rpx rgba(51, 51, 51, 0.08);" v-if="setData.service_open">
					<service></service>
				</view>
				<view v-for="(item,index) in rules" :key="index">
					<view class="info">
						<view>
							<view></view>
							<span>{{item.title}}</span>
							<view></view>
						</view>
						<view>
							 <view class="dec" v-html="item.content">{{item.content}}</view>
						 </view>
					</view>
				</view>
				<view class="footer_name" v-if="setData.copyright!=''">
					{{setData.copyright}}
				</view>
				<view v-else style="height: 40rpx;">

				</view>
			</view>
		</view>
		<view class="getMoreTimes" v-if="(activityText.has_task && taskMenuData.length>0) || isframe  ">
			<img :src="setData.task_float" @click="openTaskCenter"></img>
		</view>
		<taskCenter :show="showTask" :topImage="setData" :list="taskMenuData" @close="handlerCloseTaskCenter" @finish="handlerTaskFinish"></taskCenter>
		<modal v-if="modalData.show" :showType="modalData.type" :data="serviceData" @back="handlerInitGua" @close="handlerCloseModal"></modal>
		<modal v-if="noTimes" :showType="10" :data="serviceData"  @close="noTimes=false"></modal>
		<advertise  :data="advSet" @close="closeAdv"></advertise>
		<share v-if="showShare" :data="data" @close="showShare=false"></share>
		<guide></guide>
		<help :data="setData" v-if="showHelpModal" @hideMissionModal="hideModal"></help>
		<collectPhone  :data="data" ></collectPhone>
	</view>
</template>

<script>
	import {getGuess,ActivityInfo,chance,activityText,taskList} from '@/api/api.js'
	import {mapGetters} from 'vuex'
	import {LoginApp,checkLogin,getSystemInfo,isWeiXin,isQianfan,checkPlatform,proxyShareFun,setShare,newJumpUrl} from '@/until/QFH5.js'
	import {formatTime} from '@/until/tool.js'
	import watermarkOption from '@/until/water.js'
	import {checkHostOrImage} from '@/until/tool'
	import * as frameJs from '@/model/frameData'
	import help from "../../../components/taskCenter/help";
	export default{
		components: {help},
		computed:{
			gBackground(){
				switch(this.gType){
					case 'pink':this.gShadow="rgba(168, 11, 206, 0.27)"; return this.qiniuUrl+'canvas_pink.png'
					case 'purple':this.gShadow="rgba(75, 11, 206, 0.27)"; return this.qiniuUrl+'canvas_light.png'
					case 'orange':this.gShadow="rgba(206, 96, 11, 0.27)"; return this.qiniuUrl+'canvas_orange.png'
					case 'red':this.gShadow="rgba(206, 11, 11, 0.27)"; return this.qiniuUrl+'canvas_red.png'
					case 'yellow':this.gShadow="rgba(143, 90, 20, 0.27)"; return this.qiniuUrl+'canvas_yellow.png'
					case 'blue':this.gShadow="rgba(11, 69, 206, 0.27)"; return this.qiniuUrl+'canvas_blue.png'
					case 'green':this.gShadow="rgba(81, 141, 35, 0.27)"; return this.qiniuUrl+'canvas_green.png'
					default:this.gShadow="rgba(168, 11, 206, 0.27)"; return this.qiniuUrl+'canvas_pink.png'
				}
			},
			...mapGetters(['loginInfo','qiniuUrl','guide','updateTask','showCollectPhone'])
		},
		data(){
			return{
				advSet:{},//控制广告
				bannerDelay:'20s',//文字公告
				bannerWidth:'0px',//文字公告
				pageStatus:-1,//页面状态(刮奖蒙层显示类别) 3：图片
				restPagestatus:-1,//
				times:0,

				showDate:{},//展示日期
				showTask:false,//任务中心
				taskMenuData:[],//任务中心菜单
				gType:'',//主题类型
				gShadow:'',//刮刮乐阴影
				guaData:{ type:'text', content:'还差一点，继续刮' ,resetGua:false},//刮刮乐内容

				modalData:{show:false,type:2},//中奖弹窗
				serviceData:{},//弹窗使用的所有信息 中奖内容
				data:{ start_time:0 },//页面所有数据
				setData:{},//基础设置参数
				rules:[],//商家说明
				actid:1,//活动id
				chance:-1,//刮奖次数
				activityText:{ view_num:0, winners:[] },//动态文本数据
				taskid:156,//任务id
				taskData:null,//任务list

				showTaskModal:false,//弹窗任务
				showShare:false,//分享
				noTimes:false,//无次数
				isMoreTask:false,//是否还有未完成的任务,
				isframe:false,//被后端引用
				frameData:{ data:{ settings:{ win_popup:"" } } },
				showStatus:false,//v-clovk
				guaStatus:false,//刮奖层状态
				
				showHelpModal:false,
			}
		},
		methods:{
			//禁止划动
			moveHandle(){},
			//图片错误
			checkHost(url){
				return checkHostOrImage(url)
			},
			//隐藏
			hideModal() {
			  this.showHelpModal = false
			},
			imageError(e, index){
				this.activityText.winners[index]['avatar'] = '/static/guess/avatar.png'
			},
			//格式化时间
			settime(val){
				return formatTime(val,'YYYY-MM-DD HH:MM')
			},
			//关闭广告
			closeAdv(){
				this.advSet.start_ad_show = false
				this.advSet.popup_ad_show = false
			},
		    nextPage(val){
				if(val){
					let callback=()=>{
						console.log('执行run')
						let url ='/plugin/pages/guess/prize?id='+this.actid
						// #ifdef MP-WEIXIN
						url = './prize?id='+this.actid
						// #endif
						this.$navigateTo({ url:url})
					}
					this.getAuth(callback,null,true)

				}else{
					this.showShare = true
				}
			},
			//
			login(){
				if(this.checkPlat()){
					LoginApp(this.actid)
				}
			},
			//检查平台
			checkPlat(){
				let plat = checkPlatform()
				if(!plat){
					this.$store.dispatch('setGuideShow',4)
				}
				return plat
			},
			//计算当前次数
			sumChance(){
				let noFinish = 0
				console.log(this.taskMenuData)
				this.taskMenuData.forEach(item=>{
					if(item.is_finish==false){
							noFinish++
					}
				})
				if(noFinish>0){this.isMoreTask = true}
				else{this.isMoreTask = false}
			},
			//所有前置条件
			async getAuth(callback=()=>{},back=()=>{},isNeglect=false){
				
				let {isWechat,phone} = this.guide
				if(this.checkPlat()){
					if(!isNeglect && this.pageStatus==0){
						uni.showToast({ title:'活动还没开始呢', icon:'none' })
						return
					}
					if(!isNeglect && this.pageStatus==1){
						uni.showToast({ title:'活动已经结束了', icon:'none' })
						return
					}
					let loginStatus = await checkLogin()
					if(!loginStatus){
						this.login()
						return
					}
					//收集信息
					if(this.data.collect==1 && this.showCollectPhone=='' && isWeiXin()){
						this.$store.commit('SET_SHOWCOLLECT',true)
						this.resetGua()
						return
					}
					
					if(isQianfan()){
						if(!isWechat){
							this.$store.dispatch('setGuideShow',1)
							back()
							return
						}
						if(phone==""){
							this.$store.dispatch('setGuideShow',2)
							if(this.guaStatus){
								this.resetGua()
								this.guaStatus = false
							}
							return
						}
						callback()
					}else{
						callback()
					}
				}
			},

			//倒计时
			startTime(){
				let _this = this
				let timer = setInterval(()=>{
					let showTimer = _this.times - Math.floor(new Date()/1000)
					_this.setTime(showTimer)
					if(showTimer<=0){
						clearInterval(timer)
						if(!_this.isframe){
							_this.init()
							_this.getActivity()
						}else{
							_this.pageStatus=3
						}
					}
				},1000)
			},
			//转换时间戳
			setTime(timea){
				let day = parseInt(timea/86400)
				let hours = parseInt((timea%86400)/3600)
				let minues = parseInt((timea%86400%3600)/60)
				let ms = timea%60
				this.showDate = { day : day, hours : hours, minues : minues, ms : ms }
			},
			//刮奖图层逻辑
			async handlerGua(notInit=true){
				if(notInit && !this.checkPlat()){
					return
				}
				if(this.chance==0){
					this.sumChance()
					if(this.activityText.has_task && this.taskMenuData.length>0 && this.isMoreTask){
						uni.showToast({ title:'试试以下方式获得更多刮奖次数', icon:'none', duration:3000 })
						this.showTask = true
					}else{
						this.noTimes = true
					}
					return
				}
				let status = await checkLogin()
				if(!status){
					if(this.pageStatus!= 0  &&  this.pageStatus!=1 && !this.isframe)
						this.pageStatus=2
					return
				}
				
				
				//登录结束 检验绑定微信-引导
				if(isQianfan()){
					if(!this.guide.isWechat){
						this.$store.dispatch('setGuideShow',1)
						return
					}
					if(this.guide.phone==""){
						this.$store.dispatch('setGuideShow',2)
						return
					}
				}
				//获取次数
				this.getChance()
				if(notInit&&this.data.collect==1 && this.showCollectPhone=='' && isWeiXin()){
					this.$store.commit('SET_SHOWCOLLECT',true)
					this.pageStatus=3
					return
				}
				//重调用时 逻辑关闭刮奖广告层
				if(notInit&& this.pageStatus == 3){
					this.restPagestatus=3
					this.pageStatus =-1
				}
				//
			},
			//刮奖
			getPrize(){
				this.guaStatus = true
				let callback = ()=>{
					this.sumChance()

					getGuess({actid:this.actid}).then(res=>{
						if(res.code==0){
							this.guaData.content = res.data.msg
							this.serviceData = res.data.prize || {}
							this.serviceData.win_popup = this.setData.win_popup
							// if(this.serviceData){
								let _this = this
								setTimeout(()=>{
										_this.modalData.show=true
										if(res.data.ret==1){
											_this.modalData.type=2

										}else{
											_this.modalData.type=3
										}
								},500)
							// }
							this.getActivity()
							this.getChance()
						}else{
							this.resetGua()
							uni.showToast({ title:res.text, icon:'none', duration:3000 })
							if(this.activityText.has_task && this.isMoreTask){
								if(this.chance==0){
									this.showTask = true
								}
							}
						}
					})
				}
				let otherback = ()=>{this.resetGua()}
				this.getAuth(callback,otherback)
			},
			//刮奖结束
			handlerGuafinish(){},
			//关闭按钮
			handlerCloseModal(){
				this.modalData.show = false
			},
			//重置刮奖状态
			resetGua(){
				// console.log('reset')
				this.pageStatus = this.restPagestatus
				this.guaData.resetGua = true
				this.guaData.content = "还差一点，继续刮"
				this.guaData.isAllow = false
				this.guaStatus = false
				let _this = this
				setTimeout(()=>{
					_this.guaData.resetGua = false
					_this.guaData.isAllow = true
					console.log(_this.restPagestatus)
				},500)
			},
			//在玩一次
			handlerInitGua(){
				this.modalData.show = false
				this.resetGua()
			},
			//关闭任务
			handlerCloseTaskCenter(val){
				this.showTask = val
			},
			//完成任务
			handlerTaskFinish(val){
				if(val && val.type=='share')
					this.showShare = true
				this.initTask()
				this.getChance()
			},
			openTaskCenter(){
				let callback = ()=>{
					this.showTask = !this.showTask
				}
				this.getAuth(callback)
			},
			handlerCloseTask(){
				this.showTaskModal=false
				this.taskFinish()
				this.initTask()
				this.getChance()
			},
			async init(){
				// let res = uni.getStorageSync(this.actid) || null
				let res = null
				let nowTime =  Math.floor(new Date()/1000)
				if(!this.isframe){
						res = await ActivityInfo({actid:this.actid})
				}else{
					res = this.frameData
				}
				
				if(res.code == 0){
					// #ifdef H5
					if(res.data.status==0){
						watermarkOption.set('活动未发布')
					}
					// #endif
					this.$setTitle(res.data.title)
					uni.setStorageSync('title',res.data.title)
					this.data = res.data
					let {settings} = res.data
					
					
					
					uni.setStorageSync('platform',JSON.stringify(settings.platform))
					this.setData =settings
					this.advSet = settings
					//规则排序
					this.rules = []
					settings.sort.forEach(item=>{
						if(res.data[item]){
							let obj = {title:this.formartText(item),content:res.data[item]}
							this.rules.push(obj)
						}
					})
					this.gType = settings.guess_bg
					if(settings.layer_banner!=''){
						this.pageStatus = 3
					}
					this.$store.dispatch('serviceInfo',settings)
				}
				if(nowTime<res.data.start_time){
					this.pageStatus = 0
					this.times = res.data.start_time
					this.startTime()
				}else if(nowTime>res.data.expire_time){
					this.pageStatus = 1
				}
				this.handlerGua(false)
				let data =  res.data
				proxyShareFun(data.settings.title||data.settings.desc,data.settings.image,data.settings.desc,window.location.href)
				
				let _this = this
				this.$nextTick(()=>{
					let token = localStorage.getItem(_this.actid+'bearerToken') || null
					if(token!=null && _this.$store.state.long==0 && _this.$store.state.lat==0   && _this.data.area.type==3){
						_this.$store.dispatch('getPos')
						window.getLocationCallBackFun=()=>{}
					}
				})
			},
			formartText(val){
				let {business_intro,activity_rules,prize_intro} = this.setData.custom_desc_key
				switch(val){
					case 'business_intro':return business_intro!=''?business_intro:'商家介绍'
					case 'activity_rules':return activity_rules!=''?activity_rules:'活动规则'
					case 'prize_intro':return prize_intro!=''?prize_intro:'奖品介绍'
				}
			},
			formatImage(host,val){
				return host+val
			},
			//设置公告速度
			initCss(){
				let _this = this
				let width = 0
				uni.createSelectorQuery().in(this).selectAll(".banner_item").boundingClientRect(dom=>{
					if(dom.length>0){
						dom.forEach(item=>{ width += item.width })
						uni.getSystemInfo({
							success(res) {
								let pix = res.windowWidth/750
								//10右边间距
								_this.bannerWidth=width+pix*10*(dom.length-1)
								let pixWidth = 750  //*pix
								let nWidth = _this.bannerWidth>pixWidth?_this.bannerWidth:pixWidth
								_this.bannerDelay = parseInt(nWidth/30)+"s"
							}
						})
					}
				}).exec();
			},

			//获取刮奖次数
			getChance(){
				chance({actid:this.actid}).then(res=>{
					this.chance = res.data.num || 0
				})
			},
			//获取动态文本
			getActivity(){
				// console.log('发起请求',this.actid)
				activityText({actid:this.actid}).then(res=>{
					if(res.code ==0){
						this.activityText = res.data
						let _this = this
						// this.$nextTick(()=>{
							
						// })
						this.showStatus = true
						setTimeout(()=>{
							console.log('执行动画')
							_this.initCss()
						},300)
						if(res.data.has_task && this.taskMenuData.length==0){
							this.initTask()
						}
					}
				})
			},
			initTask(){
				taskList({actid:this.actid}).then(res=>{
					this.taskMenuData = res.data
				})
			},
			//被当做iframe引用时处理数据
			setIframeData(){
				let _this = this
				window.addEventListener('message',function(e){
					console.log('接收到了',e.data)
					let data = e.data
					//强制兼容后台数据
					_this.frameData={ code:0, data:data }
					let {settings}=data
					console.log('postmessgae',data['prize_intro'])
					_this.activityText={
						view_num:settings.view_num,
						play_num:settings.play_num,
						win_num:settings.win_num,
						winners:[{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'},{avatr:"",message:'仅供展示使用'}]
					}
					
					let {popup} = data
					switch(popup){
						case 'win_popup':
							_this.serviceData = { id: 116, redid: 0, title: "示例奖品", type: 2, }
							_this.serviceData.win_popup = _this.setData.win_popup
							_this.modalData.show=true
							_this.modalData.type=2
							break;
						case 'closewin_popup':
							_this.modalData.show=false
							break;
						case "task_popup":
							_this.taskMenuData = frameJs.taskMenuData
							_this.showTask=true
							break;
						case "closetask_popup":
							_this.showTask=false
							break;
						default:break;
					}
					_this.init()
					setTimeout(()=>{ _this.initCss() },100) },false);
			},
		},
	 	mounted() {
			console.log('mounted')
			console.log(this.actid)
			if(!this.isframe){
				this.init()
				this.getActivity()
				console.log('初始化')
			}
			let code = uni.getStorageSync(this.actid+'Invite') || 0
			if(code != 0 ){
				this.showHelpModal = true
			}
		},
		created() {
			this.actid =uni.getStorageSync('actid')
			this.$store.commit('SETACTIVITYNAME','scratchcard')
			let web  = uni.getStorageSync('WEB') || null
			console.log('created',web)
			if(web){
				console.log('post')
				this.showStatus = true
				this.isframe  = true
				this.actid = '123'
				this.setIframeData()
			}
		},
		watch:{},
		onShow() {
			console.log('触发show')

			let taskStatus =  uni.getStorageSync(this.actid+'taskStatus') || null
			if(taskStatus!=null){
				console.log('触发强刷')
				uni.setStorageSync(this.actid+'taskStatus',null)
				this.getChance()
				this.initTask()
			}
		},
		onLoad(op){
		}

	}
</script>

<style lang="scss" scoped>
	@import "./scratchcard.scss";
</style>
